package com.gzw.dms.activity;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.gzw.dms.KJ.DateTimePickDialogUtil;
import com.gzw.dms.KJ.SelectCityActivity;
import com.gzw.dms.KJ.SelectCustomerActivity;
import com.gzw.dms.KJ.SelectDepartActivity;
import com.gzw.dms.MyApplication;
import com.gzw.dms.R;
import com.gzw.dms.adapter.SelectCustomerAdapter;
import com.gzw.dms.base.BaseActivity;
import com.gzw.dms.base.BaseSpinnerAdapter;
import com.gzw.dms.bean.BackOrderInfo;
import com.gzw.dms.bean.Constant;
import com.gzw.dms.bean.ShippingOrderInfo;
import com.gzw.dms.bean.SpinnerInfo;
import com.gzw.dms.bean.UserInfo;
import com.gzw.dms.utils.FileUtil;
import com.gzw.dms.utils.HttpUtils;
import com.gzw.dms.utils.JsonUtil;
import com.gzw.dms.utils.T;
import com.gzw.dms.utils.UrlUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class BackOrderActivity extends BaseActivity {
    private Context mContext;
    private DatePickerDialog dpd;
    private ProgressDialog mProgressDialog;
    private String costomersid,user_id;
    private String shiping_order_num;
    private Button btn_sign;
    private Intent mIntent;
    private Toolbar toolbar;
    private EditText et_order_num,et_sign_startdress,
            et_custom_tel,et_sign_goodsName,et_receipt_name,et_sign_receipt_tel,et_end_dress,
            et_custom_name,et_sign_remarks,et_sign_goodsrealnum,et_sign_goodsNumber,et_remarks_order,
            et_custom,et_receipt,et_sign_goodsV,et_sign_goodsWeight,et_shopping_order_goid;
    private Spinner sp_identity;
    private TextView tv_send_mechanism,et_sign_endadress,et_end_mechanism,et_remark,et_time;
    private BackOrderInfo info;
    private String  type = "0";
    private LinearLayout layout_type,layout_time,layout_remarks,layout_enddress,layout_mechanism,layout_remark;
    private View line_sign_endadress;//终到位置下面的线
    private String initStartDateTime = ""; // 初始化开始时间

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_back_order);

    }

    @Override
    protected void initViews() {

        btn_sign = ((Button) findViewById(R.id.btn_sign));
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        et_order_num = ((EditText) findViewById(R.id.et_order_num));
        et_shopping_order_goid = ((EditText) findViewById(R.id.et_shopping_order_goid));

        et_sign_endadress = ((TextView) findViewById(R.id.et_sign_endadress));
        et_custom_name = ((EditText) findViewById(R.id.et_custom_name));
        et_custom = ((EditText) findViewById(R.id.et_custom));

        et_time = ((TextView) findViewById(R.id.et_time));
        et_sign_goodsName = ((EditText) findViewById(R.id.et_sign_goodsName));
        et_custom_tel = ((EditText) findViewById(R.id.et_custom_tel));
        et_sign_goodsV = ((EditText) findViewById(R.id.et_sign_goodsV));
        et_sign_goodsWeight = ((EditText) findViewById(R.id.et_sign_goodsWeight));
        et_sign_goodsNumber = ((EditText) findViewById(R.id.et_sign_goodsNumber));
        et_sign_goodsrealnum = ((EditText) findViewById(R.id.et_sign_goodsrealnum));
        et_sign_remarks = ((EditText) findViewById(R.id.et_sign_remark));
        et_receipt_name = ((EditText) findViewById(R.id.et_receipt_name));
        et_receipt = ((EditText) findViewById(R.id.et_receipt));
        et_sign_receipt_tel = ((EditText) findViewById(R.id.et_sign_receipt_tel));
        et_end_mechanism = (TextView) findViewById(R.id.et_end_mechanism);
        tv_send_mechanism = (TextView) findViewById(R.id.tv_send_mechanism);
        sp_identity = ((Spinner) findViewById(R.id.sp_identity));
        layout_type = (LinearLayout) findViewById(R.id.layout_type);
        layout_remarks = (LinearLayout) findViewById(R.id.layout_remarks);
        layout_time = (LinearLayout) findViewById(R.id.layout_time);
        layout_enddress = (LinearLayout) findViewById(R.id.layout_enddress);
        layout_mechanism = (LinearLayout) findViewById(R.id.layout_mechanism);
        layout_remark = (LinearLayout) findViewById(R.id.layout_remark);

        et_end_dress = ((EditText) findViewById(R.id.et_end_dress));

        et_remarks_order = ((EditText) findViewById(R.id.et_remarks_order));

        et_remark = (TextView) findViewById(R.id.et_remark);
        line_sign_endadress = (View) findViewById(R.id.line_sign_endadress);
    }

    @Override
    protected void initData() {

        readUserContent();
        mContext = this;
        toolbar.setTitle("填写运单");
        ArrayList ls = new ArrayList();
        ls.add(new SpinnerInfo("0", "退货"));
        ls.add(new SpinnerInfo("1", "调拨"));
        BaseSpinnerAdapter Adapter = new BaseSpinnerAdapter(mContext, ls);
        sp_identity.setAdapter(Adapter);
        layout_type.setVisibility(View.GONE);
 //根据不同角色 运单录入 不同显示
        UserInfo userInfo = MyApplication.getUserInfo();
        if (userInfo.getFlag().equals("3")||userInfo.getFlag().equals("4")) {
            layout_mechanism.setVisibility(View.GONE);
            et_remark.setVisibility(View.GONE);
            layout_remark.setVisibility(View.GONE);
        }
        if (userInfo.getFlag().equals("2")) {
                layout_remarks.setVisibility(View.GONE);
                layout_time.setVisibility(View.GONE);
                layout_enddress.setVisibility(View.GONE);
                line_sign_endadress.setVisibility(View.GONE);
        }
        if (userInfo.getFlag().equals("1")) {
            layout_remarks.setVisibility(View.GONE);
            layout_time.setVisibility(View.GONE);

        }


    }



    @Override
    protected void initEvents() {
        btn_sign.setOnClickListener(new myOnClick());
        toolbar.setNavigationOnClickListener(new myOnClick());
        tv_send_mechanism.setOnClickListener(new myOnClick());
        et_sign_endadress.setOnClickListener(new myOnClick());
        et_end_mechanism.setOnClickListener(new myOnClick());
        et_time.setOnClickListener(new myOnClick());

        sp_identity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                                       int arg2, long arg3) {
                SpinnerInfo spinnerInfo = (SpinnerInfo) sp_identity.getSelectedItem();
                type = spinnerInfo.getId();
                if (type.equals("0")) {
                    layout_type.setVisibility(View.GONE);

                } else if (type.equals("1")) {
                    layout_type.setVisibility(View.VISIBLE);

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
            }
        });

    }


    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.btn_sign:
                    SaveHttpClientPost();
                    break;

                case R.id.tv_send_mechanism:
                    Intent mIntent = new Intent();
                    mIntent.putExtra("type", "1");
                    mIntent.setClass(mContext, SelectCustomerActivity.class);
                    startActivityForResult(mIntent, 0);
                    break;
                case R.id.et_end_mechanism:
                    Intent mIntent1 = new Intent();
                    mIntent1.putExtra("who", "0");
                    mIntent1.setClass(mContext, SelectCityActivity.class);
                    startActivityForResult(mIntent1, 2);
                    break;
                case R.id.et_sign_endadress:
                    Intent mIntent2 = new Intent();
                    mIntent2.putExtra("who", "1");
                    mIntent2.setClass(mContext, SelectCityActivity.class);
                    startActivityForResult(mIntent2, 3);
                    break;
                case R.id.et_time:

                    SimpleDateFormat   formatter   =   new   SimpleDateFormat   ("yyyy年MM月dd日   HH:mm");
                    Date curDate =  new Date(System.currentTimeMillis());
                    initStartDateTime   =   formatter.format(curDate);

                    et_time.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {

                            DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(
                                    BackOrderActivity.this, initStartDateTime);
                            dateTimePicKDialog.dateTimePicKDialog(et_time);

                        }
                    });
                    break;
                default:
                    finish();
                    break;
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 3){
            try {
                String name = data.getStringExtra("name");
                costomersid = data.getStringExtra("id");
                tv_send_mechanism.setText(name);
            } catch (Exception e) {
                // TODO: handle exception
            }
        }else if (resultCode == 4){

            try {
                String province = data.getStringExtra("province");
                String city = data.getStringExtra("city");
                String county = data.getStringExtra("county");
                String str = province+city+county.substring(1,county.length()-1);
                et_sign_endadress.setText(str);
            } catch (Exception e) {
                // TODO: handle exception
            }
        } else if (resultCode == 2){
            try {
                String province = data.getStringExtra("province");
                String city = data.getStringExtra("city");
                String county = data.getStringExtra("county");
                String str = province+city+county.substring(1,county.length()-1);
                et_end_mechanism.setText(str);
            } catch (Exception e) {
                // TODO: handle exception
            }

        }
    }

    public void SaveHttpClientPost() {
//        if (isNull(tv_order_number)) {
//            T.showShort(mContext, "订单号不能为空");
//            return;
//        }
//
//        if (isNull(et_order_num)) {
//            T.showShort(mContext, "货运编号不能为空");
//            return;
//        }
//        if (isNull(et_sign_startdress)) {
//            T.showShort(mContext, "起运地不能为空");
//            return;
//        }
//        if (isNull(et_sign_endadress)) {
//            T.showShort(mContext, "终到位置不能为空");
//            return;
//        }
//        if (isNull(et_custom_name)) {
//            T.showShort(mContext, "发货客户名称不能为空");
//            return;
//        }
//
//        if (isNull(et_custom_tel)) {
//            T.showShort(mContext, "发货客户电话不能为空");
//            return;
//        }
//        if (isNull(et_sign_goodsName)) {
//            T.showShort(mContext, "货物名称不能为空");
//            return;
//        }
//
//        if (isNull(et_sign_goodsNumber)) {
//            T.showShort(mContext, "货物数量不能为空");
//            return;
//        }
//        if (isNull(et_sign_goodsrealnum)) {
//            T.showShort(mContext, "货物实际数量不能为空");
//            return;
//        }
//        if (isNull(et_time)) {
//            T.showShort(mContext, "提货时效不能为空");
//            return;
//        }
        if (isNull(tv_send_mechanism)) {
            T.showShort(mContext, "受理机构不能为空");
            return;
        }

        SpinnerInfo spinnerInfo = (SpinnerInfo) sp_identity.getSelectedItem();
        type = spinnerInfo.getId();
        if (info == null){
            info = new BackOrderInfo();}
        info.setTime_limitation(et_time.getText().toString());
        info.setShiping_order_num(et_order_num.getText().toString().trim());
        info.setShiping_order_goid(et_shopping_order_goid.getText().toString().trim());

        info.setCustom_tel(et_custom_tel.getText().toString().trim());
        info.setEnd_address(et_sign_endadress.getText().toString().trim());
        info.setCustom_name(et_custom_name.getText().toString().trim());
        info.setCustom_contact(et_custom.getText().toString().trim());
        info.setSend_mechanism(tv_send_mechanism.getText().toString().trim());
        info.setGoods_name(et_sign_goodsName.getText().toString().trim());
        info.setGoods_vol(et_sign_goodsV.getText().toString().trim());
        info.setGoods_weight(et_sign_goodsWeight.getText().toString().trim());
        info.setGoods_num(et_sign_goodsNumber.getText().toString().trim());
        info.setReal_num(et_sign_goodsrealnum.getText().toString().trim());
        info.setRemarks(et_sign_remarks.getText().toString().trim());
        info.setRemarks_order(et_remarks_order.getText().toString().trim());
        info.setReceipt_address(et_end_dress.getText().toString().trim());

        int order_type = Integer.parseInt(type);
        if (type.equals("0")){
            info.setOrder_type(order_type);
        }else {
            info.setOrder_type(order_type);
            info.setReceipt_name(et_receipt_name.getText().toString().trim());
            info.setReceipt_tel(et_sign_receipt_tel.getText().toString().trim());
            info.setReceipt_contact(et_receipt.getText().toString().trim());
            info.setEnd_mechanism(et_end_mechanism.getText().toString().trim());

        }
        info.setOrder_type(order_type);

        SignShipOrder signShipOrder = new SignShipOrder();
        signShipOrder.execute(info);
    }

    public class SignShipOrder extends AsyncTask<BackOrderInfo, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(BackOrderInfo... params) {
            Map<String, Object> map = new HashMap<>();
            UserInfo userInfo = MyApplication.getUserInfo();
            map.put("userInfo", userInfo);
            map.put("reverseOrderInfo", params[0]);
            String json = JsonUtil.toJson(map);
            return HttpUtils.doPost(UrlUtils.getInstance().getJavaUrl("appSaveReturnGoods"), "json=" + json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            if (isNull(result)) {
                T.showShort(mContext, "连接服务器异常");
            } else {

                if (result.indexOf("errorMsg") > 0) {
                    String errorMsg = JsonUtil.getMsg(result, "errorMsg");
                    T.showShort(mContext, errorMsg);
                } else {
                    FileUtil.getInstance().noUpload();
                    String successMsg = JsonUtil.getMsg(result, "successMsg");
                    T.showShort(mContext, successMsg);
                    Intent mIntent = new Intent();
                    //把返回数据存入Intent
                    mIntent.putExtra("result", 1);
                    //设置返回数据
                    setResult(1, mIntent);
                    finish();
                }
            }
        }
    }

    private void readUserContent() {


    }
}
